import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/common/su_icon.dart';
import 'package:love_app/db/socket_db.dart';
import 'package:love_app/enum/chat_type.dart';
import 'package:love_app/enum/socket.dart';
import 'package:love_app/model/chat_sql_model.dart';
import 'package:love_app/providers/chat_log_provider.dart';
import 'package:love_app/providers/norify_update/chat_input_update_provider.dart';
import 'package:love_app/providers/norify_update/chat_sent_icon_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/providers/socket_object_provider.dart';
import 'package:provider/provider.dart';

// 聊天页面内容
class ChatContent extends StatefulWidget {
  final int otherId; // 对方的id
  final String otherImage;

  const ChatContent({Key key, @required this.otherId, this.otherImage})
      : super(key: key);

  @override
  _ChatContentState createState() => _ChatContentState();
}

class _ChatContentState extends State<ChatContent> {
  FocusNode _focusNode; // 输入框焦点
  TextEditingController _textEditingController; // 输入框控制器
  ScrollController _scrollController; // 滚动条监听控制器

  ShareProvider _shareProvider;
  ChatLogProvider _chatLogProvider;
  ChatSentIconProvider _chatSentIconProvider;
  SocketObjetProvider _socketObjetProvider;
  ChatInputUpdateProvider _chatInputUpdateProvider;
  EasyRefreshController _easyRefreshController; // 加载控制器

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    _scrollController = ScrollController();
    _textEditingController = TextEditingController();
    _easyRefreshController = EasyRefreshController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _chatLogProvider = Provider.of<ChatLogProvider>(context, listen: false);
    _chatSentIconProvider =
        Provider.of<ChatSentIconProvider>(context, listen: false);
    _socketObjetProvider =
        Provider.of<SocketObjetProvider>(context, listen: false);
    _chatInputUpdateProvider =
        Provider.of<ChatInputUpdateProvider>(context, listen: false);
    _textEditingController.addListener(() {
      if (_textEditingController.text.isEmpty == true) {
        _chatSentIconProvider.iconData = SuIcon.chat_add;
      } else {
        _chatSentIconProvider.iconData = Icons.done;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _focusNode.unfocus();
    _textEditingController.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque, // 使其能够全部点击
      onTap: () {
        // 如果有键盘的焦点，则取消焦点
        if (_focusNode.hasFocus == true) {
          _focusNode.unfocus();
        }
      },
      child: Container(
        child: Column(
          children: <Widget>[
            _chatLog(),
            _bottomInput(),
          ],
        ),
      ),
    );
  }

  // 底部输入框
  Widget _bottomInput() {
    return Expanded(
      flex: 0,
      child: Container(
        width: Su().w(750),
        height: Su().w(97),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            _mikeIcon(),
            _input(),
            _smile(),
            _add(),
          ],
        ),
      ),
    );
  }

  // 麦克风
  Widget _mikeIcon() {
    return Container(
      child: GestureDetector(
        child: Icon(
          SuIcon.chat_mic_none,
          size: Su().w(56),
          color: Color.fromRGBO(149, 149, 149, 1),
        ),
        onTap: () {},
      ),
    );
  }

  // 输入框
  Widget _input() {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(
            width: Su().w(1),
            color: Color.fromRGBO(149, 149, 149, 1),
          ),
          borderRadius: BorderRadius.circular(Su().w(10))),
      width: Su().w(454),
      height: Su().h(73),
      child: Consumer<ChatInputUpdateProvider>(builder:
          (context, ChatInputUpdateProvider chatInputUpdateProvider, _) {
        return TextField(
          focusNode: _focusNode,
          controller: _textEditingController,
          textInputAction: TextInputAction.done,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.only(
              bottom: Su().h(10),
              left: Su().w(10),
              right: Su().w(10),
            ),
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Color.fromRGBO(149, 149, 149, 0)),
            ),
            //获得焦点下划线设为透明
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Color.fromRGBO(149, 149, 149, 0)),
            ),
          ),
        );
      }),
    );
  }

  // 表情
  Widget _smile() {
    return Container(
      child: GestureDetector(
        child: Icon(
          SuIcon.chat_face,
          size: Su().w(56),
          color: Color.fromRGBO(149, 149, 149, 1),
        ),
        onTap: () {},
      ),
    );
  }

  // + icon
  Widget _add() {
    return Container(
      child: GestureDetector(
        onTap: () {
          if (_chatSentIconProvider.iconData == Icons.done) {
            _send();
          }
        },
        child: Consumer<ChatSentIconProvider>(
          builder: (
            context,
            ChatSentIconProvider chatSentIconProvider,
            child,
          ) =>
              Icon(
            _chatSentIconProvider.iconData,
            size: Su().w(56),
            color: Color.fromRGBO(149, 149, 149, 1),
          ),
        ),
      ),
    );
  }

  // 发送消息
  Future<void> _send() async {
    _focusNode.unfocus();
    // 消息
    Map<String, dynamic> content = {
      "xAuthToken": _shareProvider.token,
      "clientType": ChatTypeToInt.getData(ChatType.text),
      'text': _textEditingController.text,
      "fd": _socketObjetProvider.fd,
    };

    Map<String, dynamic> sendDataMap = {
      "class": SocketClassToString.getClass(SocketClass.classUser),
      "action":
          SocketAccionToString.getAcction(SocketAccion.acctionPushWhispering),
      "content": content,
    };

    String json = jsonEncode(sendDataMap);
    _socketObjetProvider.channel.sink.add(json); // 添加消息到socket
    SocketDbModel socketDbModel = SocketDbModel.localSqlData(
      _shareProvider.uid,
      _textEditingController.text,
      ChatType.text,
    );
    int id = await SocketDb().insert(socketDbModel); // （自己发送的消息）插入到数据库
    Map<String, dynamic> map = {
      "id": id,
      "logId": -1,
      "sendUid": _shareProvider.uid,
      "content": _textEditingController.text,
      "type": ChatTypeToInt.getData(ChatType.text),
      "addTime": DateTime.now().millisecondsSinceEpoch,
    };
    ChatSqlModel chatSqlModel = ChatSqlModel.fromJson(map);
    _chatLogProvider.addLogInFirst(chatSqlModel);
    _chatLogProvider.notify();
    _textEditingController.text = "";
    _chatInputUpdateProvider.notify();
  }

  // 中间显示聊天记录
  Widget _chatLog() {
    return Expanded(
      flex: 1,
      child: Container(
        width: Su().w(750),
        decoration: BoxDecoration(
          gradient: const LinearGradient(colors: <Color>[
            Color.fromRGBO(254, 247, 248, 1),
            Color.fromRGBO(254, 245, 246, 1),
          ]),
        ),
        // child: _futureChatLog(),
        child: _logsCentent(),
      ),
    );
  }

  // // 异步加载容器，显示聊天记录
  // Widget _futureChatLog() {
  //   return FutureBuilder(
  //     future: _getAllChatLog(),
  //     builder: (BuildContext context, AsyncSnapshot snapshot) {
  //       if (snapshot.connectionState == ConnectionState.done) {
  //         List<ChatSqlModel> logs = _chatLogProvider.logs;
  //         return _logsCentent(logs);
  //       }
  //       // 显示loading
  //       return SuDialog.futureBuildLoding();
  //     },
  //   );
  // }

  // 获取五十条聊天记录
  Future _getAllChatLog() async {
    if ((_chatLogProvider.update == true ||
            _chatLogProvider.otherId == widget.otherId &&
                _chatLogProvider.logs.length > 0) ==
        false) {
      // 则不需要再次从数据库读取数据，直接读取chatLogProvider里面的数据
      await _findChatLogBySql(1);
    }
  }

  // 从数据库查找聊天记录
  Future<void> _findChatLogBySql(int page) async {
    int uid = _shareProvider.uid;
    int otherId = widget.otherId;
    var reslut = await SocketDb().queryPage(uid, otherId, page);
    var list = reslut.toList();
    if (list.length > 0) {
      list.forEach((item) {
        Map<String, dynamic> map = {
          "id": item['id'],
          "logId": item['id'],
          "sendUid": item['sendUid'],
          "content": item['content'],
          "type": item['type'],
          "addTime": item['addTime'],
        };
        ChatSqlModel chatSqlModel = ChatSqlModel.fromJson(map);
        _chatLogProvider.addLog(chatSqlModel);
        _chatLogProvider.otherId = widget.otherId;
      });
      _chatLogProvider.page++;
      _easyRefreshController.finishLoad(success: true, noMore: false);
    }else{
      _chatLogProvider.isEndPage = true;
      _easyRefreshController.finishLoad(success: true, noMore: true);
    }
  }

  Widget _logsCentent() {
    return EasyRefresh.custom(
      // header: SpaceHeader(),
      firstRefresh: true,
      reverse: true,
      controller: _easyRefreshController,
      enableControlFinishLoad: true,
      dragStartBehavior: DragStartBehavior.down,
      scrollController: _scrollController,
      onRefresh: _chatLogProvider.isFirst == true ? _onRefresh : null,
      onLoad: () async {
        // 触发上拉加载
        Su.suPrints(_chatLogProvider.page);
        await _findChatLogBySql(_chatLogProvider.page);
        setState(() {});
      },
      slivers: <Widget>[
        _sliver(),
      ],
    );
  }

  Future<void> _onRefresh() async {
    await _getAllChatLog();
    _chatLogProvider.isFirst = false;
    setState(() {});
  }

  // 页面的slivers
  Widget _sliver() {
    return Consumer<ChatLogProvider>(
        builder: (context, ChatLogProvider chatLogProvider, _) {
      return SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            return _everyItemWidget(chatLogProvider.logs[index]);
          },
          childCount: chatLogProvider.logs.length,
        ),
      );
    });
  }

  // 每一个聊天记录
  Widget _everyItemWidget(ChatSqlModel log) {
    return Container(
      child: log.sendUid == _shareProvider.uid
          ? _rightRighthWidget(log.content)
          : _leftRighthWidget(log.content),
    );
  }

  // 聊天记录
  Widget _leftRighthWidget(String content) {
    return Container(
      margin: EdgeInsets.only(
        left: Su().w(34),
        top: Su().h(30),
        bottom: Su().h(30),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          _leftRowHeaderImg(),
          _leftRowText(content),
        ],
      ),
    );
  }

  // 头像
  Widget _leftRowHeaderImg() {
    return Container(
      margin: EdgeInsets.only(
        right: Su().w(15),
      ),
      child: ClipOval(
        child: Image.network(
          widget.otherImage,
          width: Su().w(72),
          height: Su().w(72),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 文字
  Widget _leftRowText(String content) {
    return ConstrainedBox(
      constraints: BoxConstraints(maxWidth: Su().w(546)),
      child: Container(
        padding: EdgeInsets.all(Su().w(24)),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(Su().w(20)),
          color: Colors.white,
        ),
        child: Text(
          content,
          style: Su().textStyle(Color.fromRGBO(34, 34, 34, 1), 28),
        ),
      ),
    );
  }

  // 聊天记录
  Widget _rightRighthWidget(String content) {
    return Container(
      alignment: Alignment.centerRight,
      margin: EdgeInsets.only(
        left: Su().w(34),
        top: Su().h(30),
        bottom: Su().h(30),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _rightRowText(content),
          _rightRowHeaderImg(),
        ],
      ),
    );
  }

  // 头像
  Widget _rightRowHeaderImg() {
    return Container(
      margin: EdgeInsets.only(
        right: Su().w(15),
        left: Su().w(15),
      ),
      child: ClipOval(
        child: Image.network(
          _shareProvider.headerImage,
          width: Su().w(72),
          height: Su().w(72),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 文字
  Widget _rightRowText(String content) {
    return ConstrainedBox(
      constraints: BoxConstraints(maxWidth: Su().w(546)),
      child: Container(
        padding: EdgeInsets.only(
          left: Su().w(24),
          right: Su().w(24),
          top: Su().h(15),
          bottom: Su().h(15),
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(Su().w(20)),
          color: _shareProvider.textColor,
        ),
        child: Text(
          content,
          style: Su().textStyle(Color.fromRGBO(34, 34, 34, 1), 28),
        ),
      ),
    );
  }
}
